﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Transactions;
using System.Web.Http;
using System.Web.Http.Cors;
using AssetsSys.BLL;
using AssetsSys.Dto.Department;
using AssetsSys.Dto.Permission;
using AssetsSys.Dto.User;
using AssetsSys.model;
using AssetsSys.WebApi.Filters;
using AssetsSys.WebApi.Models.Permission;
using AssetsSys.WebApi.Models.Source;

namespace AssetsSys.WebApi.Controllers
{
    /// <summary>
    /// 用户权限
    /// </summary>
    [MyAuth]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/permission")]
    public class PermissionController : ApiController
    {
        /// <summary>
        /// 用户权限列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("infos")]
        public async Task<IHttpActionResult> GetPermissionList()
        {
            return this.SendData(await PermissionManger.GetList());
        }

        /// <summary>
        /// 用户权限列表(不包含根权限)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("infos_withoutadmin")]
        public async Task<IHttpActionResult> GetPermissionListWithoutAdmin()
        {
            return this.SendData(await PermissionManger.GetListWithoutAdmin());
        }


        /// <summary>
        /// 添加用户权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("infos")]
        public async Task<IHttpActionResult> CreatePermission(CreatePermissionViewModel model)
        {
            if (!ModelState.IsValid) return this.ErrorData(ModelState.Values.FirstOrDefault()?.Errors[0].ErrorMessage);
            return await PermissionManger.Create(model.PermissionName,model.PermissionMenu, Guid.NewGuid()) ? this.SendData("添加成功") : this.ErrorData("添加失败");
        }

        /// <summary>
        /// 获取权限内容
        /// </summary>
        /// <param name="permissionid">权限Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{permissionid}/infos")]
        public async Task<IHttpActionResult> GetPermission(Guid permissionid) {
           return this.SendData(await PermissionManger.GetById(permissionid));
        }

        /// <summary>
        /// 更新用户权限
        /// </summary>
        /// <param name="permissionid">权限Id</param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("{permissionid}/infos")]
        public async Task<IHttpActionResult> UpdateStatus(Guid permissionid, PermissionModel model)
        {
            return await PermissionManger.Update(model) ? this.SendData("修改成功") : this.ErrorData("修改失败");
        }

        /// <summary>
        /// 删除用户权限
        /// </summary>
        /// <param name="permissionid">权限Id</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{permissionid}/infos")]
        public async Task<IHttpActionResult> DeletePermission(Guid permissionid)
        {
            return await PermissionManger.Delete(permissionid) ? this.SendData("删除成功") : this.ErrorData("删除失败");
        }

        /// <summary>
        /// 初始化系统
        /// </summary>
        /// <param name="adminPhone">管理员登录账户</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("init")]
        public async Task<IHttpActionResult> InitUserPermission(string adminPhone)
        {
            if (string.IsNullOrWhiteSpace(adminPhone))
            {
                this.ErrorData("初始账户不正确");
            }
            var permissionList = await PermissionManger.GetList();
            if (permissionList.Any())
            {
                this.ErrorData("系统已经进行过初始化");
            }
            //初始权限
            var permission = new PermissionModel
            {
                Id = Guid.NewGuid(),
                PermissionName = "管理员",
                PermissionMenu = "[{\"Name\":\"资产信息\",\"Icon\":\"&#xe6b5;\",\"Href\":\"\",\"Child\":" +
                                 "[{\"Name\":\"资产列表\",\"Icon\":\"\",\"Href\":\"AssetsList.html\",\"Child\":null}," +
                                 "{\"Name\":\"部门资产\",\"Icon\":\"\",\"Href\":\"DepartmentAssets.html\",\"Child\":null}]}," +
                                 "{\"Name\":\"资产变更\",\"Icon\":\"&#xe723;\",\"Href\":\"\",\"Child\":" +
                                 "[{\"Name\":\"资产变动\",\"Icon\":\"\",\"Href\":\"AssetsChange.html\",\"Child\":null}," +
                                 "{\"Name\":\"资产报修\",\"Icon\":\"\",\"Href\":\"ProblemReport.html\",\"Child\":null}," +
                                 "{\"Name\":\"资产维修\",\"Icon\":\"\",\"Href\":\"Repair.html\",\"Child\":null}]}," +
                                 "{\"Name\":\"角色管理\",\"Icon\":\"&#xe726;\",\"Href\":\"\",\"Child\":" +
                                 "[{\"Name\":\"用户管理\",\"Icon\":\"\",\"Href\":\"UserManage.html\",\"Child\":null}," +
                                 "{\"Name\":\"部门管理\",\"Icon\":\"\",\"Href\":\"DepartmentManage.html\",\"Child\":null}]}]"
            };
            //初始部门
            var department = new DepartmentModel()
            {
                Id = Guid.NewGuid(),
                DepartmentName = "校产处",
                PermissionId = permission.Id
            };
            //用户
            var user = new UserModel()
            {
                UserName = "管理员",
                PassWord = "670b14728ad9902aecba32e22fa4f6bd", //默认密码 MD5(000000)
                Email = "",
                PhoneNum = adminPhone,
                DepartmentId = department.Id,
            };
            //初始化权限
            await PermissionManger.Create(permission.PermissionName, permission.PermissionMenu, permission.Id);
            //初始化部门
            await DepartmentManger.Create(department.DepartmentName, department.PermissionId, department.Id);
            //初始化用户
            await UserManger.CreateUser(user.UserName, user.PassWord, user.Email, user.PhoneNum, user.DepartmentId);

            return this.SendData("系统初始化成功，管理员登录账号："+ adminPhone+"默认密码：000000");
        }

    }
}
